﻿using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace HttpBot
{
    public class PictureDownloadBot
    {
        public static void Download(string url, string cookie, string root_path, DicParam person, IRow row)
        {
            var uri = new Uri(url);
            // var content = File.ReadAllText("a.html",Encoding.GetEncoding("GBK"));
            var content = HttpHelper.Post(url, cookie, person);
            File.AppendAllText("error.txt", content + "\r\n");
            Regex regex = new Regex("<image.*src=\"(.*?)\".*?>");
            Regex regexResult = new Regex("<input type=\"hidden\" name=\"checkresult\" value=\"00\">(.*?)</div>");
            var match = regex.Match(content);
            var match1 = regexResult.Match(content);

            //判断超时
            if (content.LastIndexOf("login.jsp") != -1)
            {
                Console.WriteLine("登陆超时请退出本程序重新登陆......");
                Console.ReadLine();
                Environment.Exit(0);
            }

            var retStr = "没有数据";
            if (match.Groups.Count <= 1)
            {
                //标记数据
                row.CreateCell(8).SetCellValue(retStr);
                WriteLogHelper.WriteLine(HttpUtility.UrlDecode(person.Params[2].Value, Encoding.GetEncoding("gb2312")), person.Params[1].Value, retStr);
                return;
            }
            else
            {
                try
                {
                    retStr = match1.Groups[1].Value;
                    //标记数据
                    row.CreateCell(8).SetCellValue(retStr);
                    WriteLogHelper.WriteLine(HttpUtility.UrlDecode(person.Params[2].Value, Encoding.GetEncoding("gb2312")), person.Params[1].Value, retStr);
                }catch(Exception ex)
                {
                    File.AppendAllText("error.txt", "尝试解析返回结果出现异常\r\n");
                    File.AppendAllText("error.txt",ex.ToString());
                }
            }

            var image = match.Groups[1].Value;
            File.AppendAllText("error.txt", "ImageUrl:" + image + "\r\n");
            string imageUrl = uri.Scheme + "://" + uri.Host + "/picp/" + image;
            HttpHelper.Download(imageUrl, url, Path.Combine(root_path, person.Params[1].Value + ".jpg"), cookie);
            WriteLogHelper.WriteLine(HttpUtility.UrlDecode(person.Params[2].Value, Encoding.GetEncoding("gb2312")), person.Params[1].Value, "照片已下载");
        }
    }
}